<template>
  <div class="service-container">
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <h3>车辆管理</h3>
          <div class="header-right">
            <el-button type="primary" @click="openAddDialog" class="add-btn">
              <el-icon><Plus /></el-icon>添加车辆
            </el-button>
            <div class="search-toggle-area">
              <el-button class="search-toggle-button" @click="toggleSearchBar">
                <el-icon><Search /></el-icon>
              </el-button>
              <el-form :inline="true" :model="queryParams" class="search-form" :class="{'is-hidden': !showSearchBar}" ref="queryForm">
                <el-form-item label="车牌号">
                  <el-input v-model="queryParams.plate_number" placeholder="请输入车牌号" clearable></el-input>
                </el-form-item>
                <el-form-item label="所属类型">
                  <el-select v-model="queryParams.owner_type" placeholder="请选择所属类型" clearable style="width: 160px;">
                    <el-option label="企业员工" value="employee"></el-option>
                    <el-option label="访客" value="visitor"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="车辆类型">
                  <el-select v-model="queryParams.vehicle_type" placeholder="请选择车辆类型" clearable style="width: 160px;">
                    <el-option label="小轿车" value="小轿车"></el-option>
                    <el-option label="SUV" value="SUV"></el-option>
                    <el-option label="货车" value="货车"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleQuery">查询</el-button>
                  <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </template>

      <div class="filter-container" v-if="false">
        <el-form :inline="true" :model="queryParams" class="filter-form">
          <el-form-item label="车牌号">
            <el-input v-model="queryParams.plate_number" placeholder="请输入车牌号" clearable></el-input>
          </el-form-item>
          <el-form-item label="所属类型">
            <el-select v-model="queryParams.owner_type" placeholder="请选择所属类型" clearable>
              <el-option label="企业员工" value="employee"></el-option>
              <el-option label="访客" value="visitor"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="车辆类型">
            <el-select v-model="queryParams.vehicle_type" placeholder="请选择车辆类型" clearable>
              <el-option label="小轿车" value="小轿车"></el-option>
              <el-option label="SUV" value="SUV"></el-option>
              <el-option label="货车" value="货车"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table 
        v-loading="loading" 
        :data="vehicleList" 
        border 
        stripe 
        :header-cell-style="{background:'#f5f7fa', color:'#606266'}"
      >
        <el-table-column prop="vehicle_id" label="ID" width="100" align="center" />
        <el-table-column prop="plate_number" label="车牌号" width="150" align="center" />
        <el-table-column prop="brand" label="品牌" width="130" align="center" />
        <el-table-column prop="model" label="型号" width="130" align="center" />
        <el-table-column prop="color" label="颜色" width="110" align="center" />
        <el-table-column prop="vehicle_type" label="车辆类型" width="120" align="center" />
        <el-table-column label="所属人" width="150" align="center">
          <template #default="scope">
            <span v-if="scope.row.user">
              {{ scope.row.user.name }}
              <el-tag size="small" type="success">员工</el-tag>
            </span>
            <span v-else-if="scope.row.visitor">
              {{ scope.row.visitor.name }}
              <el-tag size="small" type="warning">访客</el-tag>
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="register_date" label="注册日期" width="130" align="center" />
        <el-table-column label="操作" width="190" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-if="vehicleList.length === 0 && !loading" description="暂无车辆数据" class="empty-data-placeholder"></el-empty>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑车辆对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加车辆' : '编辑车辆'"
      v-model="dialogVisible"
      width="600px"
      append-to-body
    >
      <el-form
        ref="vehicleFormRef"
        :model="vehicleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="车牌号" prop="plate_number">
          <el-input v-model="vehicleForm.plate_number" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="vehicleForm.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="vehicleForm.model" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-input v-model="vehicleForm.color" placeholder="请输入颜色" />
        </el-form-item>
        <el-form-item label="车辆类型" prop="vehicle_type">
          <el-select v-model="vehicleForm.vehicle_type" placeholder="请选择车辆类型" style="width: 100%">
            <el-option label="小轿车" value="小轿车"></el-option>
            <el-option label="SUV" value="SUV"></el-option>
            <el-option label="货车" value="货车"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属类型" prop="owner_type">
          <el-select v-model="vehicleForm.owner_type" placeholder="请选择所属类型" style="width: 100%" @change="handleOwnerTypeChange">
            <el-option label="企业员工" value="employee"></el-option>
            <el-option label="访客" value="visitor"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属人" prop="owner_id">
          <el-select 
            v-model="vehicleForm.owner_id" 
            placeholder="请选择所属人" 
            style="width: 100%" 
            filterable 
            remote 
            :remote-method="handleOwnerSearch"
            :loading="ownerLoading"
          >
            <el-option 
              v-for="item in ownerOptions" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="注册日期" prop="register_date">
          <el-date-picker 
            v-model="vehicleForm.register_date" 
            type="date" 
            placeholder="选择注册日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getVehicleList, addVehicle, updateVehicle, deleteVehicle } from '@/api/assets'
import { Search, Plus } from '@element-plus/icons-vue'

export default {
  name: 'VehicleList',
  setup() {
    // 查询参数
    const queryParams = reactive({
      page: 1,
      limit: 10,
      plate_number: '',
      owner_type: '',
      vehicle_type: ''
    })

    // 列表数据
    const vehicleList = ref([])
    const total = ref(0)
    const loading = ref(false)
    const showSearchBar = ref(false)

    // 对话框
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const vehicleFormRef = ref(null)
    
    // 表单数据
    const vehicleForm = reactive({
      vehicle_id: null,
      plate_number: '',
      brand: '',
      model: '',
      color: '',
      vehicle_type: '',
      owner_type: '',
      owner_id: null,
      register_date: new Date()
    })

    // 表单校验规则
    const rules = reactive({
      plate_number: [
        { required: true, message: '请输入车牌号', trigger: 'blur' },
        { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{5,6}$/, message: '请输入正确的车牌号', trigger: 'blur' }
      ],
      vehicle_type: [
        { required: true, message: '请选择车辆类型', trigger: 'change' }
      ],
      owner_type: [
        { required: true, message: '请选择所属类型', trigger: 'change' }
      ],
      owner_id: [
        { required: true, message: '请选择所属人', trigger: 'change' }
      ],
      register_date: [
        { required: true, message: '请选择注册日期', trigger: 'change' }
      ]
    })

    // 所属人选择相关
    const ownerOptions = ref([])
    const ownerLoading = ref(false)

    // 切换搜索栏显示状态
    const toggleSearchBar = () => {
      showSearchBar.value = !showSearchBar.value;
    };

    // 获取车辆列表
    const fetchVehicleList = async () => {
      loading.value = true
      try {
        const response = await getVehicleList(queryParams)
        if (response.data && response.data.code === 200) {
          vehicleList.value = response.data.data.results
          total.value = response.data.data.count
        } else {
          ElMessage.error('获取车辆列表失败')
        }
      } catch (error) {
        console.error('获取车辆列表失败:', error)
        ElMessage.error('获取车辆列表失败')
      } finally {
        loading.value = false
      }
    }

    // 查询
    const handleQuery = () => {
      queryParams.page = 1
      fetchVehicleList()
    }

    // 重置查询
    const resetQuery = () => {
      queryParams.plate_number = ''
      queryParams.owner_type = ''
      queryParams.vehicle_type = ''
      handleQuery()
    }

    // 处理页码变化
    const handleCurrentChange = (val) => {
      queryParams.page = val
      fetchVehicleList()
    }

    // 处理每页数量变化
    const handleSizeChange = (val) => {
      queryParams.limit = val
      queryParams.page = 1
      fetchVehicleList()
    }

    // 打开添加对话框
    const openAddDialog = () => {
      dialogType.value = 'add'
      resetForm()
      dialogVisible.value = true
    }

    // 打开编辑对话框
    const openEditDialog = (row) => {
      dialogType.value = 'edit'
      resetForm()
      nextTick(() => {
        vehicleForm.vehicle_id = row.vehicle_id
        vehicleForm.plate_number = row.plate_number
        vehicleForm.brand = row.brand
        vehicleForm.model = row.model
        vehicleForm.color = row.color
        vehicleForm.vehicle_type = row.vehicle_type
        
        if (row.user) {
          vehicleForm.owner_type = 'employee'
          vehicleForm.owner_id = row.user.user_id
          ownerOptions.value = [{ id: row.user.user_id, name: row.user.name }]
        } else if (row.visitor) {
          vehicleForm.owner_type = 'visitor'
          vehicleForm.owner_id = row.visitor.visitor_id
          ownerOptions.value = [{ id: row.visitor.visitor_id, name: row.visitor.name }]
        }
        
        vehicleForm.register_date = new Date(row.register_date)
        dialogVisible.value = true
      })
    }

    // 重置表单
    const resetForm = () => {
      vehicleForm.vehicle_id = null
      vehicleForm.plate_number = ''
      vehicleForm.brand = ''
      vehicleForm.model = ''
      vehicleForm.color = ''
      vehicleForm.vehicle_type = ''
      vehicleForm.owner_type = ''
      vehicleForm.owner_id = null
      vehicleForm.register_date = new Date()
      ownerOptions.value = []
      
      // 重置表单校验结果
      if (vehicleFormRef.value) {
        vehicleFormRef.value.resetFields()
      }
    }

    // 处理所属类型变化
    const handleOwnerTypeChange = () => {
      vehicleForm.owner_id = null
      ownerOptions.value = []
    }

    // 搜索所属人
    const handleOwnerSearch = async (query) => {
      if (query === '') {
        ownerOptions.value = []
        return
      }

      ownerLoading.value = true
      try {
        // 根据不同的所属类型，调用不同的API
        // 这里只是示例，实际需要根据后端API接口来实现
        setTimeout(() => {
          if (vehicleForm.owner_type === 'employee') {
            ownerOptions.value = [
              { id: 1, name: '张三' },
              { id: 2, name: '李四' }
            ]
          } else if (vehicleForm.owner_type === 'visitor') {
            ownerOptions.value = [
              { id: 1, name: '王五' },
              { id: 2, name: '赵六' }
            ]
          }
          ownerLoading.value = false
        }, 500)
      } catch (error) {
        console.error('搜索所属人失败:', error)
        ownerLoading.value = false
      }
    }

    // 提交表单
    const handleSubmit = () => {
      vehicleFormRef.value.validate(async (valid) => {
        if (!valid) return

        // 日期格式处理函数
        const formatDate = (date) => {
          if (!date) return null;
          if (typeof date === 'string') {
            // 如果是字符串，尝试提取YYYY-MM-DD部分
            return date.split('T')[0];
          } else if (date instanceof Date) {
            // 如果是Date对象，格式化为YYYY-MM-DD
            return date.toISOString().split('T')[0];
          }
          return null;
        };

        const data = {
          plate_number: vehicleForm.plate_number,
          brand: vehicleForm.brand,
          model: vehicleForm.model,
          color: vehicleForm.color,
          vehicle_type: vehicleForm.vehicle_type,
          register_date: formatDate(vehicleForm.register_date) // 格式化日期
        }

        // 根据所属类型，设置不同的ID字段
        if (vehicleForm.owner_type === 'employee') {
          data.user_id = vehicleForm.owner_id
        } else if (vehicleForm.owner_type === 'visitor') {
          data.visitor_id = vehicleForm.owner_id
        }

        try {
          if (dialogType.value === 'add') {
            await addVehicle(data)
            ElMessage.success('添加成功')
          } else {
            await updateVehicle(vehicleForm.vehicle_id, data)
            ElMessage.success('更新成功')
          }
          dialogVisible.value = false
          fetchVehicleList()
        } catch (error) {
          console.error('提交失败:', error)
          ElMessage.error('提交失败')
        }
      })
    }

    // 删除车辆
    const handleDelete = (row) => {
      ElMessageBox.confirm(`确认删除车牌号为 ${row.plate_number} 的车辆信息吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteVehicle(row.vehicle_id)
          ElMessage.success('删除成功')
          fetchVehicleList()
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }).catch(() => {})
    }

    onMounted(() => {
      fetchVehicleList()
    })

    return {
      queryParams,
      vehicleList,
      total,
      loading,
      showSearchBar,
      dialogVisible,
      dialogType,
      vehicleForm,
      vehicleFormRef,
      rules,
      ownerOptions,
      ownerLoading,
      toggleSearchBar,
      handleQuery,
      resetQuery,
      handleCurrentChange,
      handleSizeChange,
      openAddDialog,
      openEditDialog,
      handleOwnerTypeChange,
      handleOwnerSearch,
      handleSubmit,
      handleDelete
    }
  }
}
</script>

<style scoped>
.service-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 80px);
}

.search-bar {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

/* 搜索区域 */
.search-toggle-area {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.search-toggle-button {
  font-size: 20px;
  color: #606266;
  align-self: center;
  margin-right: 15px;
  transition: all 0.2s;
  cursor: pointer;
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.03);
  border: 1px solid rgba(0, 0, 0, 0.05);
  z-index: 10;
  margin-bottom: 0;
}

.search-toggle-button:hover {
  color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
  border-color: rgba(64, 158, 255, 0.2);
}

.search-form {
  max-width: 1000px;
  width: auto;
  overflow: hidden;
  transition: max-width 0.4s ease-in-out, opacity 0.4s ease-in-out, background-color 0.4s ease-in-out, box-shadow 0.4s ease-in-out, padding 0.4s ease-in-out, margin-left 0.4s ease-in-out, height 0.4s ease-in-out, min-height 0.4s ease-in-out;
  opacity: 1;
  background-color: transparent;
  border-radius: 8px;
  padding: 0 20px;
  box-shadow: none;
  pointer-events: auto;
  margin-left: 15px;
  white-space: nowrap;
  height: 35px;
  min-height: 35px;
}

.search-form.is-hidden {
  max-width: 0;
  opacity: 0;
  padding: 0;
  margin-left: 0;
  height: 0;
  min-height: 0;
  background-color: transparent;
  box-shadow: none;
  pointer-events: none;
}

/* 调整搜索表单项的底部外边距 */
:deep(.search-form .el-form-item) {
  margin-bottom: 0;
  margin-right: 15px;
  display: inline-flex;
  align-items: center;
}

:deep(.search-form .el-form-item__label) {
  padding-right: 8px;
}

:deep(.table-card .el-card__header) {
  background-color: #f9fafc;
  padding: 15px 20px;
}

:deep(.table-card .el-card__body) {
  padding: 20px;
}

.pagination-container {
  margin-top: 25px;
  display: flex;
  justify-content: flex-end;
  padding: 12px 15px;
  background-color: #f9fbfd;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.empty-data-placeholder {
  margin-top: 40px;
}

.add-btn {
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 搜索框el-input优化 */
:deep(.el-input__inner) {
  border-color: #e0e5ed !important;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-input__inner:focus) {
  border-color: rgba(64, 158, 255, 0.4) !important;
}

:deep(.el-input__inner::placeholder) {
  color: #aebccf;
}

/* 按钮el-button优化 */
:deep(.el-button--primary) {
  background-color: rgba(64, 158, 255, 0.1) !important;
  color: #606266 !important;
  border-color: rgba(64, 158, 255, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--primary:hover) {
  background-color: rgba(64, 158, 255, 0.15) !important;
  border-color: rgba(64, 158, 255, 0.3) !important;
}

/* Default Button */
:deep(.el-button--default) {
  background-color: #ffffff !important;
  color: #606266 !important;
  border-color: #dcdfe6 !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--default:hover) {
  background-color: #f7f9fa !important;
  border-color: #c8d3dd !important;
}

/* Danger Button */
:deep(.el-button--danger) {
  background-color: rgba(245, 108, 108, 0.1) !important;
  color: #F56C6C !important;
  border-color: rgba(245, 108, 108, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--danger:hover) {
  background-color: rgba(245, 108, 108, 0.15) !important;
  border-color: rgba(245, 108, 108, 0.3) !important;
}
</style> 